# encoding: utf-8
# author: 侯佳涛
# file_name: 10.baidu_transform
# create_time: 2021/5/19, 下午8:39
"""
Query String Parameters参数：发送请求时需要携带的参数，如果携带的参数不正确就不能正确返回数据，例如中文到英文的 中国-->China 日本-->Japan需要的参数就不一样
"""
import requests
import json
import sys


class King:
    def __init__(self, word, mode='en_zh'):
        # url
        self.url = 'https://ifanyi.iciba.com/index.php?c=trans&m=fy&client=6&auth_user=key_ciba&sign=0f70cbecb4e597f6'

        # 请求头
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36'
        }

        # 请求体
        self.data = {
            'from': 'en',
            'to': 'zh',
            'q': word
        }

        if mode == 'zh_en':
            self.url = 'https://ifanyi.iciba.com/index.php?c=trans&m=fy&client=6&auth_user=key_ciba&sign=fcc710ee8531159d'
            self.data = {
                'from': 'zh',
                'to': 'en',
                'q': word
            }

    def get_data(self):
        """
        发送请求获取数据
        :return:
        """
        response = requests.post(self.url, data=self.data, headers=self.headers)

        return response.content

    def parse_data(self, data):
        try:
            print(json.loads(data)['content']['out'])
        except:
            print(json.loads(data))

    def run(self):
        response = self.get_data()

        self.parse_data(response)


if __name__ == '__main__':
    word = sys.argv[2]
    mode = sys.argv[1]
    king = King(word, mode)
    king.run()



